package com.gregbugaj.nscaffold;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.RootClass;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.Table;
import org.hibernate.mapping.Value;
import org.hibernate.type.Type;

import org.hsqldb.persist.HsqlProperties;
import org.hsqldb.server.Server;
import org.hsqldb.server.ServerAcl.AclFormatException;

import com.gregbugaj.nscaffold.domain.Keyword;
import com.gregbugaj.nscaffold.domain.Product;

/**
 * Hello world!
 * 
 */
public class App {
	public static void main(String[] args) throws MappingException, HibernateException, IOException, AclFormatException {
		initDB();
		
		File f = new File("hibernate.cfg.xml");
		System.out.println(f.getAbsolutePath());
		AnnotationConfiguration cfg = new AnnotationConfiguration();
		cfg.configure(f);

		SessionFactory sessions = cfg.buildSessionFactory();
		Session session = sessions.openSession();

		Iterator<RootClass> iter = cfg.getClassMappings();
		while (iter.hasNext()) {
			RootClass rc = iter.next();
			System.out.println(rc);
			Iterator<Property> iterProp  = rc.getPropertyClosureIterator();
			while (iterProp.hasNext()) {
				Property rcProp = iterProp.next();
				System.out.println(" =  "+rcProp);
				System.out.println("     "+rcProp.getName());
				System.out.println("     "+rcProp.getType());
				System.out.println("  ");
			}
	}

		
		Product prod=new Product();
		List<Keyword> keywords=new ArrayList<Keyword>();
		keywords.add(new Keyword(1, "Red"));
		keywords.add(new Keyword(2, "Blue"));
		prod.setKeywords(keywords);
		
		Transaction tx = null;
		try {
			tx = session.beginTransaction();

			session.save(prod);
			tx.commit();
			tx = session.beginTransaction();
			Product p = (Product) session.load(Product.class, 1L);
			
			System.out.println(p);

			tx.commit();
		
			//System.exit(0);
		
		} catch (HibernateException he) {
			if (tx != null)
				tx.rollback();
			throw he;
		} finally {
			session.close();
		}
	}

	public static void initDB() throws IOException, AclFormatException {
		HsqlProperties p = new HsqlProperties();

		p.setProperty("server.database.0", "file:c:/temp/nscaffold");
		p.setProperty("server.dbname.0", "an_alias");
		// set up the rest of properties
		Server server = new Server();
		server.setDatabaseName(0, "test");
		server.setProperties(p);
		server.setLogWriter(null); // can use custom writer
		server.setErrWriter(null); // can use custom writer
		server.start();

	}
}
